import {moment} from "../../node-test";

const {axios} = require('../../node-test');
import {ReadyState} from "../interfaces";
import waitUpState from "./1waitUp";
import weightState from "./2weight";
import state from "./state";
import settings from "../settings";
import weighter from "../weight";
import plate from "../plate";
import player from "../player";
import controller from "../controller";
import log from "../logger";


class ReadyStateImpl implements ReadyState {
    name = "ReadyState"
    plateLock: boolean = false;

    init(): void {
        state.clear();
        if (settings.barrierGate === 'inout') {
            plate.manualTrigger(true)
        }
    }

    leave(): void {
        if (settings.barrierGate === 'inout') {
            plate.manualTrigger(false)
        }
    }

    toWaitUpState(vehicleNumber: string, inout: 'in' | 'out') {
        if (state.stateContext.name === 'ReadyState') {
            state.addPlate(vehicleNumber, inout, 100);
            state.stateContext = waitUpState;
        }
        this.plateLock = false
    }

    plate(vehicleNumber: string, inout: 'in' | 'out') {
        if (!state.enable) {
            player.say("禁止过磅，请联系管理员")
            return;
        }
        // 如果是out模式，没有重量识别的车号是错误的
        if (settings.barrierGate !== 'inout') {
            return;
        }
        // 判断是否是后退车辆
        if (vehicleNumber === state.backVehicle.carNum) {
            const currentTimestamp = new Date().getTime()
            // 3分钟后可用
            if (currentTimestamp - state.backVehicle.time < 60 * 1000 * 1.5) {
                log.info("后退操作后，1.5分钟内不可用")
                return;
            }
        }
        if (!this.plateLock && state.addPlate(vehicleNumber, inout)) {
            // 加锁，防止重复请求
            this.plateLock = true;
            // 避免长时间脏数据
            state.clear();
            // 不派车让不让进厂
            if (settings.vehicleEnter) {
                this.vehicleEnterRequest(vehicleNumber).then((res) => {
                    if (res === 'openGateway') {
                        this.plateLock = false;
                        controller.openGateway(inout);
                    } else {
                        this.toWaitUpState(vehicleNumber, inout);
                    }
                }).catch((msg) => {
                    this.plateLock = false;
                    // 清空状态相关信息
                    state.clear();
                    player.say(msg);
                });
            } else {
                this.toWaitUpState(vehicleNumber, inout);
            }
        }
    }

    active(R: boolean[]): void {
    }

    weight_data(weight: number, wen: boolean): void {
        // 无前置杆类型上磅
        if (weight > 0.5) {
            state.stateContext = weightState;
            weighter.emit('weight_data', weight, wen)
        }
    }

    driverRequest(type: string): void {
    }

    do_weigh(weight: number, deductionWeight: number): void {
    }

    vehicleEnterRequest(vehicleNumber: string): Promise<string> {
        return new Promise((resolve, reject) => {
            // 添加上磅时间参数，后台校验连续过磅时间差
            const params = {
                vehicleName: vehicleNumber,
                platformId: settings.platformId,
                time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            };
            axios.post(settings.url + '/api/order/bangDan/vehicleEnterWithType', params)
                .then((resp1: any) => {
                    log.info("vehicleEnterRequest response:", resp1.data);
                    if (resp1.data.code !== '0000') {
                        // 禁止过磅了，请求白名单，是白名单的，则直接全部抬杆
                        const parameters = {carNum: vehicleNumber};
                        axios.post(settings.url + '/api/weigh/gateway/carEnter/' + settings.deviceName,
                            parameters).then((resp: any) => {
                            if (resp.data.code === '0000') {
                                resolve("openGateway");
                            } else {
                                reject(resp1.data.msg);
                            }
                        }).catch(() => {
                            reject(resp1.data.msg);
                        });
                    } else {
                        // 过磅类型，判断仪表是否正常工作
                        if (!weighter.available) {
                            reject("仪表工作异常，禁止上磅");
                        } else {
                            state.isPurchase = resp1.data.data.type === 'SM';
                            state.manualDoWeigh = resp1.data.data.manualDoWeigh || false;
                            state.primaryWeight = resp1.data.data.primaryWeight || 0;
                            state.expectedNetWeight = resp1.data.data.expectedNetWeight || 0;
                            state.isSale = resp1.data.data.type === "TM";
                            state.isSecond = resp1.data.data.state === 'First' || resp1.data.data.state === 'Confirm';
                            state.closeSaleBtnWeighing = resp1.data.data.saleCloseBtnWeigh || false;
                            state.warehouse = resp1.data.data.warehouse || "";
                            state.location = resp1.data.data.location || "";
                            state.senderName = resp1.data.data.senderName || "";
                            state.customerName = resp1.data.data.customerName || "";
                            if (settings.weighType.includes(resp1.data.data.type)) {
                                resolve("ok");
                            } else {
                                let msg = ""
                                if (resp1.data.data.type === 'TM') {
                                    msg = "不允许销售车辆过磅，请前往销售磅进行过磅";
                                }
                                if (resp1.data.data.type === 'SM') {
                                    msg = "不允许采购车辆过磅，请前往采购磅进行过磅";
                                }
                                if (resp1.data.data.type === 'DD') {
                                    msg = "不允许短倒车辆过磅，请前往短倒磅进行过磅";
                                }
                                reject(msg);
                            }
                        }
                    }
                })
                .catch(() => {
                    reject("请求服务器错误，禁止上磅")
                });
        })
    }
}

const readyState = new ReadyStateImpl();
export default readyState;